package org.edith.shiro.controller;

import org.edith.shiro.dataobject.SysUserDO;
import org.edith.shiro.response.CommonResponse;
import org.edith.shiro.util.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户登录
 */
@RestController
@RequestMapping("/user")
public class UserLoginController {

    /**
     * 登录
     */
    @PostMapping("/login")
    public CommonResponse login(@RequestBody SysUserDO sysUserDO) {
        Map<String, Object> map = new HashMap<>();

        //验证身份和登陆
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(sysUserDO.getUsername(), sysUserDO.getPassword());
        //进行登录操作
        subject.login(token);
        map.put("token", ShiroUtils.getSession().getId().toString());
        return CommonResponse.success(map);
    }

    /**
     * 注销
     */
    @PostMapping("/logout")
    public CommonResponse logout() {
        SysUserDO userInfo = ShiroUtils.getUserInfo();
        ShiroUtils.deleteCache(userInfo.getUsername(),true);
        ShiroUtils.logout();
        return CommonResponse.success();
    }
}